package com.bite.book.config;

import com.bite.book.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:DELL
 * Date:2025-06-06
 * Time:22:04
 */
//对于结果统一处理
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {//是否要对其进行包装
        return true;
    }

    @SneakyThrows
    @Override//怎么包装
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof Result){//如果是result类型，则直接返回
            return body;
        }
        if(body instanceof String){//处理String类型
            return objectMapper.writeValueAsString(Result.success(body));
        }
        return Result.success(body);//不是Result类型则对其进行封装
    }
}
